<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mpush extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function pushAll($notification){
        
        $sql_ios = "SELECT DISTINCT key_ios FROM `push_key` WHERE NOT (key_ios <=> NULL)";
        $sql_android = "SELECT DISTINCT key_android FROM `push_key` WHERE NOT (key_android <=> NULL)";
        
        $key_ios = $this->db->query($sql_ios)->result_array();
        $key_android = $this->db->query($sql_android)->result_array();
        
        $arr_ios = array();
        $arr_android = array();
        foreach($key_ios AS $key_1 => $value_1)
        {
            if(!in_array($value_1['key_ios'], array(null, '')))
            {
                $arr_ios[] = $value_1['key_ios'];
            }
        }
        foreach($key_android AS $key_2 => $value_2)
        {
            if(!in_array($value_2['key_android'], array(null, '')))
            {
                $arr_android[] = $value_2['key_android'];
            }
        }
        
        $this->push_ios($notification,$arr_ios);
        $this->send_push_notification($arr_android,$notification);
        return 200;
    }

    private function push_ios($notification,$arr_ios)
    {
        //$TEXT_ALERT =  isset($_REQUEST['mes'])? $_REQUEST['mes'] : 'Bạn có tin nhắn từ VTV';
        $TEXT_ALERT = $notification;
        $BADGE = 1;
        $SOUND = 'default';
        $SERVER_ID = '';
        $NAME = '';
        $SANBOX = 1;
        //e1edea3201896340c0a3ee204159dab77e52107b86671c35158600b88e217562
        //$token1 = 'd35adca952d11e59e436edd93293d8cc5ac1c9f161fe480f9ad15258c5f6ff71';
        //$deviceTokenList = array($token1);
        $deviceTokenList = $arr_ios;
        $payload = array();
        $payload['aps'] = array('alert' => $TEXT_ALERT, 'badge' => $BADGE, 'sound' => $SOUND);
        $payload['server'] = array('serverId' => $SERVER_ID, 'name' => $NAME);
        $payload = json_encode($payload);
        
        
        
        if ($SANBOX) {
        	$apnsHost = 'gateway.sandbox.push.apple.com';
        }else{
        	$apnsHost = 'gateway.push.apple.com';
        }
        $apnsPort = 2195;
        $apnsCert = PROJECT_PATH2.'/push_development.pem';
        
        //make connection
        $streamContext = stream_context_create();
        stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
        $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
        
        if ($apns == NULL || $error != NULL) {
        	//echo "Error when connect to " . $apnsPort . ', err string ' . $errorString;
        	return 201;
        }

        
        //echo "connect success\n";
        foreach ($deviceTokenList as $deviceToken) {
        	//echo "Add token $deviceToken\n";
        	//build message
        	$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
        	fwrite($apns, $apnsMessage);
        }
        @socket_close($apns);
        fclose($apns);
        
        return 200;
    }
    
    private function send_push_notification($registation_ids, $message) {
        //die(GOOGLE_API_KEY);
        //die('d');
        $url = 'https://android.googleapis.com/gcm/send';

        $fields = array(
            'registration_ids' => $registation_ids,
            'data' => array( 'price' => $message ),
        );
        $headers = array(
            'Authorization: key='.GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        //print_r($headers);
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            //die('Curl failed: ' . curl_error($ch));
            return 201;
        }

        // Close connection
        curl_close($ch);
        //echo $result;
        return 200;
    }
    
}